package db

import (
	"gopkg.in/yaml.v2"
	"os"
	"path"
	"tinyrdm/server/config"
)

type LocalStorage struct {
	ConfPath string
}

// NewLocalStore returns a localStore instance.
func NewLocalStore(filename string) *LocalStorage {
	return &LocalStorage{
		ConfPath: path.Join(config.Config.DBDir, filename),
	}
}

// Load reads the given file in the user's configuration directory and returns
// its contents.
func (l *LocalStorage) Load(out interface{}) error {
	d, err := os.ReadFile(l.ConfPath)
	if err != nil && os.IsNotExist(err) {
		return nil
	}
	if err != nil {
		return err
	}
	err = yaml.Unmarshal(d, out)
	return err
}

// Store writes data to the user's configuration directory at the given
// filename.
func (l *LocalStorage) Store(in interface{}) error {
	dir := path.Dir(l.ConfPath)
	if err := ensureDirExists(dir); err != nil {
		return err
	}
	data, err := yaml.Marshal(&in)
	if err != nil {
		return err
	}
	if err := os.WriteFile(l.ConfPath, data, 0777); err != nil {
		return err
	}
	return nil
}

// ensureDirExists checks for the existence of the directory at the given path,
// which is created if it does not exist.
func ensureDirExists(path string) error {
	_, err := os.Stat(path)
	if os.IsNotExist(err) {
		if err = os.Mkdir(path, 0777); err != nil {
			return err
		}
	}
	return nil
}
